import { defineStore } from 'pinia';
import {computed, ref} from 'vue';
import { fetchStatusList, updateStatus, deleteStatus, createStatus } from '@/api/modules/status';
import useMessage from "@/plugin/useMessage"; // 引入接口

export const useStatusStore = defineStore('status', () => {
  const count = ref(0);
  const statusList = ref([]);
  //筛选结果
  const searchQuery = ref<string>();
  // 获取列表（从后台获取）
  const fetchList = async () => { // 修改方法名
    try {
      let res = await fetchStatusList();
      statusList.value = res.data;
    } catch (error) {
      console.error('Error in fetchList:', error);
    }
  };

  // 更新状态（提交到后台）
  const update = async (id, newStatus) => { // 修改方法名
    try {
      await updateStatus(id, newStatus);
      const index = statusList.value.findIndex(item => item.id === id);
      if (index !== -1) {
        statusList.value[index] = { ...statusList.value[index], ...newStatus };
      }
    } catch (error) {
      console.error('Error in update:', error);
    }
  };

  // 删除状态（提交到后台）
  const remove = async (id:number) => { // 修改方法名
    try {
      let res = await deleteStatus(id);
      if(res.code === 200){
        statusList.value = statusList.value.filter(item => item.id !== id);
      }
      useMessage(res.code,res.message)
    } catch (error) {
      useMessage(500,error)
    }
  };
  // 筛选状态（根据表述）
  const search = (type:string)=>{
    if (!type) return statusList.value; // 如果输入为空，返回完整列表
    return statusList.value.filter(item =>
        item.type.toLowerCase().includes(type.toLowerCase())
    );
  }
  return {
    count,
    statusList,
    fetchList,
    update,
    remove,
    search,
    searchQuery
  };
}, { persist: true });